package com.example.service1.provider.config;

import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
import java.util.Collections;

@Configuration
public class SentinelConfig {

    @PostConstruct
    public void init(){
        loadFlowRules(" /service1/get");
    }

    /**
     * 如果想要代码方式，设置限流规则，着以下面这种方式进行调用使用
     * sentinel静态持久化方式
     * @param resource
     */
    public static void loadFlowRules(String resource){
        FlowRule rule = new FlowRule();
        //资源名称,可以是任意字符串
        rule.setResource(resource);
        //限流阈值
        rule.setCount(5);
        //限流阈值类型,设置为QPS。即每秒QPS大于5时，触发限流
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //针对的调用来源
        rule.setLimitApp("default");
        //调用关系限流策略,默认按照资源本身
        rule.setStrategy(RuleConstant.STRATEGY_DIRECT);
        //限流效果，默认直接拒绝
        rule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
        //是否集群限流
        rule.setClusterMode(false);
        FlowRuleManager.loadRules(Collections.singletonList(rule));
    }

    /**
     * 声明一个SentinelResource注解的切面类
     * 详细理解源码：
     * https://github.com/alibaba/Sentinel/wiki/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8#%E5%AE%9A%E4%B9%89%E8%B5%84%E6%BA%90
     */
    @Bean
    public SentinelResourceAspect sentinelResourceAspect(){
        return new SentinelResourceAspect();
    }


}
